package com.kedi.usercenter.pcauthority.service.impl;

import java.util.HashSet;
import java.util.List;

import com.alibaba.fastjson.JSON;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.kedi.usercenter.pcauthority.entity.AdministratorAuthority;
import com.kedi.usercenter.pcauthority.entity.AdministratorRole;
import com.kedi.usercenter.pcauthority.entity.AuthLableSource;
import com.kedi.usercenter.pcauthority.service.Authority;
import com.kedi.usercenter.read.mapper.PcAuthority;
import com.kedi.usercenter.utils.JsonUtils;

import javax.annotation.Resource;

/**
 * 该类是项目启动时候加载数据库中所有的角色信息以及角色所拥有的资源信息。
 * @author Zyred
 * @date 2019-7-30
 */
@Service
public class AuthorityImpl implements Authority{

	//@Value("${redis.key.prefix}")
	private String prefix = "role:";

	@Autowired
	PcAuthority pcAuthority;
	
	@Autowired
    StringRedisTemplate redisTemplate;

	/**
	 * 加载系统访问资源到Redis中
	 */
	@Override
	public void loadAuthorityToRedies(){
		List<AdministratorRole> roles = pcAuthority.selectAdministratorRole();

		if(roles == null && roles.isEmpty()){
			return;
		}

		List<AdministratorAuthority> authoritys = null;
		List<AuthLableSource> authLableSources = null;
		for( AdministratorRole administratorRole:roles){
			HashSet<AuthLableSource> set = new HashSet<AuthLableSource>();
			authoritys = pcAuthority.selectAdministratorAuthority(
			        administratorRole.getAdministratorRoleId());

			if(authoritys == null && authoritys.isEmpty()){
				return;
			}

			for( AdministratorAuthority administratorAuthority:authoritys){
				authLableSources = pcAuthority.selectAuthLableSource(
				        administratorAuthority.getAdministratorAuthorityId());
				administratorAuthority.setAuthLableSourceList(authLableSources);

				if(authLableSources == null && authLableSources.isEmpty()){
					return;
				}
				for(AuthLableSource authLableSource:authLableSources){
					set.add(authLableSource);
				}
			}

			administratorRole.setList(authoritys);
			administratorRole.setSet(set);
			String json = JsonUtils.objectToJson(administratorRole);
			redisTemplate.opsForValue().set(String.valueOf(
			        prefix + administratorRole.getRolename()), json);
			
		}

		
	}
}
